package com.yang.service.impl;



import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.yang.domain.entity.Shop;
import com.yang.enums.CacheStrategyEnum;
import com.yang.mapper.ShopMapper;
import com.yang.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yang.strategy.context.CacheStrategyContext;
import com.yang.constants.SystemConstants;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static com.yang.constants.RedisConstants.*;
import static com.yang.enums.AppHttpCodeEnum.SHOP_NULL;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yang
 * @since 2022-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheStrategyContext cacheStrategyContext;
    @Resource
    private ShopMapper shopMapper;
    @Resource
    private RedissonClient redissonClient;

    @Override
    public Shop queryShopById(Long id) {
        // 执行缓存空值策略
        Shop shop = cacheStrategyContext.executeCacheStrategy(
                CACHE_SHOP_KEY,
                id,
                Shop.class,
                this::getById,
                CACHE_SHOP_TTL,
                TimeUnit.MINUTES,
                CacheStrategyEnum.BLOOM_FILTER);

        Assert.notNull(shop,SHOP_NULL.getMsg());

        return shop;
    }


    @Override
    public void updateShop(Shop shop) {

        Assert.notNull(shop,"店铺不存在");

        Long shopId = shop.getId();


        RLock lock = redissonClient.getLock(LOCK_SHOP_KEY + shopId);


        lock.lock(2, TimeUnit.SECONDS);

        try {

            this.updateById(shop);

            stringRedisTemplate.delete(CACHE_SHOP_KEY + shopId);

        }finally {
            lock.unlock();
        }
    }

    @Override
    public List<Shop> queryShopByType(Integer typeId, Integer current, Double x, Double y) {

        // 1.判断是否需要根据坐标查询
        if (x == null || y == null) {
            return shopMapper.findAllShopByType(typeId,current,SystemConstants.DEFAULT_PAGE_SIZE);
        }

        // 2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        // 3.查询redis、按照距离排序、分页。结果：shopId、distance
        String key = SHOP_GEO_KEY + typeId;

        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );
        // 4.解析出id
        if (results == null) {
            return Collections.emptyList();
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页了，结束
            return Collections.emptyList();
        }
        // 4.1.截取 from ~ end的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            // 4.2.获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 4.3.获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });

        // 5.根据id查询Shop
        String idStr = StrUtil.join(",", ids);

        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();

        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        // 6.返回
        return shops;
    }
}
